package top.kangyaocoding.ecommerce.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * 描述: AES加解密工具类
 *
 * @author K·Herbert
 * @since 2025-02-16 下午9:00
 */
@Component
public class AESUtil {

    // 固定密钥（128位，16字节）
    private final String AES_KEY;

    // 构造函数注入 AES_KEY
    public AESUtil(@Value("${data.aes.key}") String aesKey) {
        this.AES_KEY = aesKey;
    }

    // AES加密算法
    private static final String ALGORITHM = "AES";

    // 加密
    public String encrypt(String data) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(AES_KEY.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    // 解密
    public String decrypt(String encryptedData) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(AES_KEY.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decryptedBytes);
    }
}
